import Taro from '@tarojs/taro'
import interceptors from './interceptors'

const BASE_URL = process.env.NODE_ENV === 'development' ? '/api' : ''

// 注册各种拦截器
interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem))

export default {
  baseOptions(params, method = 'GET') {
    const { url, data } = params
    const option = {
      ...params,
      url: `${BASE_URL}${url}`,
      data,
      method,
      header: {
        'content-type': params.contentType || 'application/json',
        // 'Authorization': Taro.getStorageSync('Authorization'),
        ...params.header
      }
    }
    return Taro.request(option)
  },

  request(params) {
    return this.baseOptions(params)
  },

  get(url, data = {}) {
    const params = { url, data }
    return this.baseOptions(params)
  },

  post(url, data, ...extraParams) {
    const params = { url, data, extraParams }
    return this.baseOptions(params, 'POST')
  },

  put(url, data = {}) {
    const params = { url, data }
    return this.baseOptions(params, 'PUT')
  },

  delete(url, data = '') {
    const params = { url, data }
    return this.baseOptions(params, 'DELETE')
  }
}
